#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int tickets = 1;

void* allen(void* arg) {
  int flag = 1;
  while(flag) {
    pthread_mutex_lock(&lock);
    pthread_mutex_lock(&lock);
    if (tickets <= 10) {
      printf("allen sell ticket %d\n", tickets);
      usleep(1000*20);// 20ms
      ++tickets;
    }
    else flag = 0;
    pthread_mutex_unlock(&lock);
    usleep(1000*20);// 20ms
  }
  return NULL;
}

void* luffy(void* arg) {
  int flag = 1;
  while(flag) {
    pthread_mutex_lock(&lock);
    if (tickets <= 10) {
      printf("luffy sell ticket %d\n", tickets);
      usleep(1000*80);// 80ms
      ++tickets;
    }
    else flag = 0;
    pthread_mutex_unlock(&lock);
    usleep(1000*80);// 80ms
  }
  return NULL;
}
int main() {
  pthread_t tid1, tid2;
  pthread_create(&tid1, NULL, allen, NULL);
  pthread_create(&tid2, NULL, luffy, NULL);
  pthread_join(tid1, NULL);
  pthread_join(tid2, NULL);
  return 0;
}
